<template>
  <AppDialogForm
    title="分配权限"
    :confirm="handleSubmit"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-tree
      ref="treeRef"
      :data="rightsList"
      show-checkbox
      default-expand-all
      node-key="id"
      :default-checked-keys="defKeys"
      :props="treeProps"
    >
    </el-tree>
  </AppDialogForm>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { setRoleRights } from "@/api/roles.js";

const props = defineProps({
  roleInfo: {
    type: Object,
    default: () => {},
  },
  rightsTree: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(["success"]);
const treeRef = ref(null);
const rightsList = ref([]);
const treeProps = {
  children: "children",
  label: "authName",
};
const loading = ref(false);
const defKeys = ref([]);

const loadInfo = () => {
  if (!props.roleInfo) {
    return;
  }
  rightsList.value = [...props.rightsTree];
  getLeafKeys(props.roleInfo, defKeys.value);
};

// 通过递归形式获取角色下所有三级权限的ID，并保存到defKeys数组中
const getLeafKeys = (node, arr) => {
  // 如果当前node节点不包含children属性则是三级节点
  if (!node.children) {
    return arr.push(node.id);
  }
  node.children.forEach((item) => {
    getLeafKeys(item, arr);
  });
};

const handleDialogOpen = () => {
  loadInfo();
};

const handleSubmit = async () => {
  loading.value = true;
  const keys = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()];
  const idStr = keys.join(",");
  await setRoleRights(props.roleInfo.id, idStr).finally(() => {
    loading.value = false;
  });
  ElMessage.success("分配权限成功");
  emit("success");
};
const handleDialogClosed = () => {
  defKeys.value = [];
};
</script>

<style lang="scss" scoped></style>
